package com.derbysoft.synxisadapter.dswitch3.service.impl;

import com.derbysoft.dswitch.remote.hotel.dto.ErrorDTO;
import com.derbysoft.synxisadapter.commons.exception.ChannelNotFoundException;
import com.derbysoft.synxisadapter.commons.exception.ProviderSideException;
import com.derbysoft.synxisadapter.commons.model.Channel;
import com.derbysoft.synxisadapter.commons.repository.ChannelRepository;
import com.derbysoft.synxisadapter.commons.utils.ErrorMessageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

/**
 * User: jason
 * Date: 2012-11-28
 */
public abstract class DS3AbstractService {
    protected static final String SYSTEM = "System";

    @Value("${provider}")
    protected String provider;

    @Value("${dswitch3.adapter}")
    protected String adapter;

    @Autowired
    protected ChannelRepository channelRepository;

    protected ErrorDTO createDS3ErrorDTO(Exception ex) {
        ErrorDTO errorDTO = new ErrorDTO();
        errorDTO.setCode(SYSTEM);
        errorDTO.setSource(ex instanceof ProviderSideException ? provider : adapter);
        errorDTO.setMessage(ErrorMessageUtils.buildErrorMessage(ex));
        return errorDTO;
    }

    protected Channel loadChannel(String channelCode) {
        Channel channel = channelRepository.findByCode(channelCode);
        if (channel == null) {
            throw new ChannelNotFoundException(channelCode);
        }
        return channel;
    }
}
